package com.kye.express.business.scanner;

import android.arch.lifecycle.Lifecycle;

import com.google.gson.reflect.TypeToken;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.ErrorView;
import com.kye.express.contract.base.view.LoadingView;
import com.kye.express.contract.base.view.RxView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.SharedPreferencesConfig;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.order.scan_code_order.IsCanScanCodeToAddOrder;
import com.kye.model.bean.order.scan_code_order.ScanCodeOrderAddress;
import com.kye.model.bean.user.User;
import com.kye.model.bean.waybill_search.RequestWaybillQuery;
import com.kye.model.bean.waybill_search.ResultWaybillQuery;
import com.kye.model.bean.waybill_search.WaybillHistoryModel;
import com.kye.model.datasource.OrderDataSource;
import com.kye.model.service.WaybillQueryService;

import java.util.List;

import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public interface WaybillScannerActivityContract {

    interface WaybillScannerView extends RxView, LoadingView, ErrorView {

        void onLoaded(ResultWaybillQuery datas, String searchString);

        void onCanScanCodeAddOrder(String customerCode, ScanCodeOrderAddress addressData);

        void onCanNotScanCodeAddOrder();
    }

    class WaybillScannerPresenter extends BasePresenter<WaybillScannerView> {

        private OrderDataSource mOrderDataSource;


        @Override
        public void bind(WaybillScannerView view) {
            super.bind(view);
            mOrderDataSource = new OrderDataSource();
        }

        public void searchWaybill(final String expressNum) {
            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .flatMap(new Function<User, SingleSource<OpenApiResult<ResultWaybillQuery>>>() {
                        @Override
                        public SingleSource<OpenApiResult<ResultWaybillQuery>> apply(User user) throws Exception {
                            return RetrofitManager.getInstance().createOpenApiService(WaybillQueryService.class)
                                    .waybillQuery(new RequestWaybillQuery(expressNum, user.getPhone()));
                        }
                    })
                    .doOnSuccess(new Consumer<OpenApiResult<ResultWaybillQuery>>() {
                        @Override
                        public void accept(OpenApiResult<ResultWaybillQuery> resultWaybillQueryOpenApiResult) throws Exception {
                            List<WaybillHistoryModel> waybillHistoryModelList = SharedPreferencesManager.get(SharedPreferencesConfig.KEY_HISTORY_WAYBILL, new TypeToken<List<WaybillHistoryModel>>() {
                            }.getType());
                            waybillHistoryModelList.add(new WaybillHistoryModel(resultWaybillQueryOpenApiResult.getData().getWaybillNumber() + "", System.currentTimeMillis()));
                            SharedPreferencesManager.commit(SharedPreferencesConfig.KEY_HISTORY_WAYBILL, waybillHistoryModelList);
                        }
                    })
                    .compose(getView().getProvider().<OpenApiResult<ResultWaybillQuery>>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((new OpenApiResultObserver<ResultWaybillQuery>() {

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<ResultWaybillQuery> result, ResultWaybillQuery data) {
                            getView().onLoaded(data, expressNum);
                        }

                        @Override
                        public void onApiError(OpenApiResult<ResultWaybillQuery> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    }));
        }

        public void isCanAddOrder(String customCode) {
            mOrderDataSource.isCanAddOrder(customCode, null)
                    .compose(getView().bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<IsCanScanCodeToAddOrder>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<IsCanScanCodeToAddOrder> result, IsCanScanCodeToAddOrder isCanScanCodeToAddOrder) {
                            if (isCanScanCodeToAddOrder.isOrdersType()) {
                                final ScanCodeOrderAddress addressData = new ScanCodeOrderAddress();
                                addressData.setContactsPhone(isCanScanCodeToAddOrder.getContactNumber());
                                addressData.setContacts(isCanScanCodeToAddOrder.getContacts());
                                addressData.setIsDefault(isCanScanCodeToAddOrder.isDefault());
                                addressData.setProvince(isCanScanCodeToAddOrder.getProvince());
                                addressData.setCity(isCanScanCodeToAddOrder.getCity());
                                addressData.setArea(isCanScanCodeToAddOrder.getArea());
                                addressData.setAddress(isCanScanCodeToAddOrder.getAddress());
                                addressData.setGuid(isCanScanCodeToAddOrder.getGuid());
                                getView().onCanScanCodeAddOrder(isCanScanCodeToAddOrder.getCompanyCode(), addressData);
                            } else {
                                getView().onCanNotScanCodeAddOrder();
                            }
                        }

                        @Override
                        public void onApiError(OpenApiResult<IsCanScanCodeToAddOrder> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

    }
}
